package net.hky365.lowcode.magic.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import lombok.extern.slf4j.Slf4j;
import net.hky365.lowcode.magic.utils.LoggerHelper;
import net.hky365.shop.framework.common.util.CommonUtils;
import org.slf4j.Logger;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.ssssssss.magicapi.datasource.model.MagicDynamicDataSource;
import org.ssssssss.script.MagicScriptEngine;
import org.ssssssss.script.functions.DynamicModuleImport;

import javax.sql.DataSource;
import java.util.Map;

@Slf4j
@Configuration
public class MagicDataSourceConfig {
    @Bean
    public MagicDynamicDataSource magicDynamicDataSource(Map<String, DataSource> dataSources) {
        MagicDynamicDataSource dynamicDataSource = new MagicDynamicDataSource();
        if (CommonUtils.isEmpty(dataSources)) {
            return dynamicDataSource;
        }
        int index = 0;
        for (Map.Entry<String, DataSource> item : dataSources.entrySet()) {
            DataSource dataSource = item.getValue();
            if (dataSource instanceof DynamicRoutingDataSource) {
                dynamicDataSource.setDefault(dataSource);
                for (Map.Entry<String, DataSource> entry : ((DynamicRoutingDataSource) dataSource).getDataSources().entrySet()) {
                    dynamicDataSource.add(entry.getKey(), entry.getValue());
                }
            }
            index++;
            dynamicDataSource.add(CommonUtils.nonEmptyOrDefault(item.getKey(), CommonUtils.toString(index)), dataSource);
        }
        return dynamicDataSource;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void setLogModule() {
        // 重写log模块, 避免log 输出日志级别不方便控制

        // 一共有如下两种情况, 第一种通过将 url 路径转为包格式来进行控制, 第二种通过将名称转为包格式来进行控制
        // 模板/获取模板信息(/yk/amis/template/detail/{id})
        // 模板/获取模板信息
        if (MagicScriptEngine.getDefaultImports().isEmpty()) {
            log.warn("override the magic `log` module failed");
        }
        MagicScriptEngine.addDefaultImport("log", new DynamicModuleImport(Logger.class, LoggerHelper::getLogger));
    }
}
